import ScrollBarLayout from '@/components/ScrollBarLayout';
import { AutoComplete, Card, Col, Empty, Form, Input, Row, Table, message } from 'antd';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ContractOppositeCountContext } from '../common';
import { getTableColumn, handleOppositeData, handleSumStr, mergeOppositeData } from '../mconfig';
import { SearchOutlined } from '@ant-design/icons';

import pageStyles from '@/common/pageLayout.less';

//引入echarts主模块
import * as echarts from 'echarts';
// 引入柱状图
import 'echarts/lib/chart/bar';
// 引入饼状图
import 'echarts/lib/chart/pie';
// 引入标题和提示框
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import ReactDOM from 'react-dom';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';
import Cls from 'classnames';
import { getOppositeDataGrid, reportOppositeByStepService } from '../services';
import { getKeyRouter } from '@/utils';

let allOppositeView: any; //相对方收付款统计

export const OppositeCountEchartsView: React.FC<ContractAllCountAPI.IOppositeCountEchartsView> = ({
  oppositeSearchInfo,
  searchParams,
  setOppositeSearchInfo,
}) => {
  /** 引入上下文 */
  const { echartsDetailInfo, styleFixCls, curRes, stepTypeValue } = useContext(ContractOppositeCountContext);

  const [searchForm] = Form.useForm();

  let allOppositeCountRef: any = useRef(); //相对方收付款统计Ref

  /** 获取相对方列表 */
  const { oppositeList, getManageData } = getOppositeDataGrid(curRes, {});

  /** 保存分页参数  */
  const [pageSizeObj, setPageSizeObj] = useState<any>({
    page: 1,
    rows: 10,
  });

  /** 保存搜索参数 */
  const [searchValue, setSearchValue] = useState<string>('');

  // /** 相对方数据 */
  const oppoListMemo = useMemo(() => {
    let oppoList: Record<string, any>[] = [];
    if (searchValue && oppositeList?.length > 0) {
      oppositeList?.forEach((item: any) => {
        if (item?.oppositeName?.includes(searchValue)) {
          oppoList?.push({
            value: item?.oppositeName,
            label: item?.oppositeName,
            key: item?.id,
          });
        }
      });
    }
    return oppoList;
  }, [searchValue, oppositeList]);

  useEffect(() => {
    if (echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}') {
      const { oppositeNameList, payNumNameList, paySumNameList, putNumNameList, putSumNameList } = handleOppositeData(echartsDetailInfo);

      /** 渲染合同相对方汇总统计 */
      oppositeAllBar({
        oppositeNameList,
        payNumNameList,
        paySumNameList,
        putNumNameList,
        putSumNameList,
      });
    }
  }, [echartsDetailInfo]);

  /**保存搜索后的数据 */
  const oppoCountListMemo = useMemo(() => {
    if (searchForm?.getFieldsValue()?.supplierID) {
      return mergeOppositeData(oppositeSearchInfo);
    } else {
      return mergeOppositeData(echartsDetailInfo);
    }
  }, [oppositeSearchInfo, echartsDetailInfo, searchValue]);
  /**
   * 处理返回 tooltip 数据
   * @param tipInfo
   * @param payNumInfo
   * @param putNumInfo
   * @param putSumInfo
   * @returns
   */
  const renderTooltip = (tipInfo: Record<string, any>, payNumInfo: Record<string, any>, putNumInfo: Record<string, any>, putSumInfo: Record<string, any>) => {
    return `
      ${tipInfo?.name}
      <br />
      ${tipInfo?.marker}付款数量：${payNumInfo?.value} 个
      <br />
      <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#91cc75;"></span>${
        tipInfo?.seriesName
      }：${handleSumStr(Number(tipInfo?.value))}
      `;
    // <br />
    // ${tipInfo?.marker}收款数量：${putNumInfo?.value} 个
    // <br />
    // ${tipInfo?.marker}收款金额：${handleSumStr(Number(putSumInfo?.value))}
  };

  /** 相对方汇总统计 */
  const oppositeAllBar = (dataInfo: Record<string, any>) => {
    if (allOppositeView != null && allOppositeView != '' && allOppositeView != undefined) {
      allOppositeView?.dispose();
    }

    const { oppositeNameList, payNumNameList, paySumNameList, putNumNameList, putSumNameList } = dataInfo;

    oppositeNameList.reverse();

    // 柱状的总统计图
    const option: any = {
      title: {
        text: '合同相对方汇总统计',
        left: 'center',
      },
      grid: {
        left: '8%',
        bottom: '5%',
        top: '14%',
        right: '8%',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
        formatter: (params) => {
          const tipInfo: Record<string, any> = params?.[0];

          // 付款数量
          const payNumInfo: Record<string, any> | any = payNumNameList?.find((item: any) => item?.name == tipInfo?.name);

          // 收款数量
          const putNumInfo: Record<string, any> | any = putNumNameList?.find((item: any) => item?.name == tipInfo?.name);

          // 收款金额
          const putSumInfo: Record<string, any> | any = putSumNameList?.find((item: any) => item?.name == tipInfo?.name);

          return renderTooltip(tipInfo, payNumInfo, putNumInfo, putSumInfo);
          // return tipInfo?.name + '<br/>' + tipInfo?.seriesName + ' : ' + tipInfo?.value;
        },
      },
      // legend: {
      //   data: ['收款数量', '付款数量', '收款金额', '付款金额'],
      //   padding: [30, 5],
      // },
      toolbox: {
        show: true,
        feature: {
          magicType: {
            mark: { show: true },
            show: true,
            type: ['line', 'bar'],
            title: {
              line: '切换为折线图',
              bar: '切换为柱状图',
            },
          },
        },
        right: '4%',
        padding: [30, 5],
      },
      calculable: true,
      yAxis: [
        {
          type: 'category',
          data: oppositeNameList,
          name: 'TOP10(相对方)',
          nameTextStyle: {
            color: '#000', // 字体颜色
            fontWeight: 'bold', // 字体粗细
          },
          axisLabel: {
            interval: 0,
            rotate: 40,
            formatter: (value: any) => {
              const newValue: string = value?.length > 8 ? `${value?.slice(0, 8)}...` : value;
              return value != 'null' ? newValue : '--';
            },
          },
        },
      ],
      xAxis: [
        {
          type: 'value',
          name: '金额/元',
          position: 'left',
          alignTicks: true,
          axisLine: {
            show: true,
          },
        },
        // {
        //   type: 'value',
        //   name: '数量/个',
        //   position: 'right',
        //   alignTicks: true,
        //   axisLine: {
        //     show: true,
        //   },
        //   axisLabel: {
        //     formatter: (value) => {
        //       return Number.isInteger(value) ? value : '';
        //     },
        //   },
        // },
      ],
      series: [
        // {
        //   name: '收款数量',
        //   type: 'bar',
        //   data: putNumNameList,
        //   xAxisIndex: 1,
        //   label: {
        //     show: true,
        //     position: 'right',
        //   },
        // },
        // {
        //   name: '付款数量',
        //   type: 'bar',
        //   data: payNumNameList,
        //   xAxisIndex: 1,
        //   label: {
        //     show: true,
        //     position: 'right',
        //   },
        // },
        // {
        //   name: '收款金额',
        //   type: 'bar',
        //   data: putSumNameList,
        //   label: {
        //     show: true,
        //     position: 'right',
        //   },
        // },
        {
          name: '付款金额',
          type: 'bar',
          data: paySumNameList?.reverse(),
          label: {
            show: true,
            position: 'right',
          },
          itemStyle: {
            color: (params: any) => {
              let colorList = ['#11d1da', '#91c7ae', '#61a0a8', '#ca8622', '#d48265', '#2f4554', '#749f83', '#c23531'];
              return colorList[params.dataIndex];
            },
          },
        },
      ],
    };

    /** 合同数量汇总 */
    const allOppsiteViewDiv: any = ReactDOM.findDOMNode(allOppositeCountRef?.current);
    allOppositeView = echarts.init(allOppsiteViewDiv);
    allOppositeView.setOption(option, true);
  };

  // 分页页数 和数据条数改变
  const handlePaginationChange = (page: number, pageSize: number) => {
    let params = {
      ...pageSizeObj,
      page: page,
      rows: pageSize,
    };
    setPageSizeObj(params);
  };

  /** 统计回调 */
  const allCountCallback = (res: any) => {
    if (res && res?.msgFlag) {
      setOppositeSearchInfo(res?.obj);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入接口 */
  const { reportOppositeByStepRun, reportOppositeByStepLoading } = reportOppositeByStepService(curRes, allCountCallback);

  const onSearchRun = () => {
    const searchValue = searchForm?.getFieldsValue();
    let stepStr: number = 2;
    if (stepTypeValue == '月') {
      stepStr = 2;
    } else if (stepTypeValue == '年') {
      stepStr = 3;
    }
    let params: Record<string, any> = {
      ...searchParams,
      ...searchValue,
      choiceStyle: stepStr,
    };
    reportOppositeByStepRun(params);
  };

  /** 处理下拉框 */
  // const selectDomMemo = useMemo(() => {
  //   let oppoList: Record<string, any>[] = []
  //   if (searchValue && oppositeList?.length > 0) {
  //     oppositeList?.forEach((item: any) => {
  //       if (item?.oppositeName?.includes(searchValue)) {
  //         oppoList?.push(item)
  //       }
  //     })
  //   }
  //   return (
  //     <Select
  //       placeholder="合同相对方"
  //       loading={oppositeLoading}
  //       mode="multiple"
  //       maxTagCount={1}
  //       allowClear={false}
  //       onDropdownVisibleChange={(open) => {
  //         if (!open) {
  //           onSearchRun();
  //         } else {
  //           getManageData({});
  //         }
  //       }}
  //       onSearch={(value) => {
  //         setSearchValue(value)
  //       }}
  //     >
  //       {oppoList?.map((item: any) => {
  //         return (
  //           <Select.Option value={item?.id} key={item?.id}>
  //             {item?.oppositeName}
  //           </Select.Option>
  //         );
  //       })}
  //     </Select>
  //   )
  // }, [searchValue])

  return (
    <div className={`${styleFixCls}allCountDiv-bodyBox`}>
      <ScrollBarLayout style={{ padding: '0px' }}>
        <Row>
          <Col span={24}>
            <div style={{ height: 550 }} className={`${styleFixCls}allCountDiv-bodyBox-colDiv`}>
              {echartsDetailInfo && JSON.stringify(echartsDetailInfo) != '{}' ? (
                <div className={`${styleFixCls}allCountDiv-bodyBox-echartsDiv`} ref={allOppositeCountRef} />
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无【合同相对方汇总统计】数据" />
              )}
            </div>
          </Col>
          <Col style={{ paddingTop: 4, height: 400 }} span={24}>
            <Card
              className={Cls(pageStyles['page-view-cardView'], `${styleFixCls}searchFormCard`)}
              title={
                <div className={`${styleFixCls}searchFormCard-titleBox`}>
                  <Form form={searchForm}>
                    <Form.Item name="supplierName">
                      <AutoComplete
                        options={oppoListMemo}
                        value={searchValue}
                        notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                        onSelect={(value, option) => {
                          searchForm?.setFieldsValue({
                            supplierID: option?.key,
                          });
                          setSearchValue(value);
                        }}
                        onDropdownVisibleChange={(open) => {
                          if (!open) {
                            onSearchRun();
                          } else {
                            getManageData({});
                          }
                        }}
                      >
                        <Input
                          suffix={<SearchOutlined />}
                          onChange={(e) => {
                            if (!e?.target?.value) {
                              searchForm?.resetFields();
                              onSearchRun();
                            }
                            setSearchValue(e?.target?.value);
                          }}
                          placeholder="请按相对方名称搜索"
                          allowClear={true}
                        />
                      </AutoComplete>
                    </Form.Item>
                    <Form.Item name={'supplierID'} style={{ display: 'none' }}>
                      <Input hidden />
                    </Form.Item>
                  </Form>
                </div>
              }
              bodyStyle={{
                padding: '10px 0px 0px',
              }}
            >
              <div className={Cls(pageStyles['listTable-zIndexStyle'], `${styleFixCls}cardTable`)}>
                <Table
                  columns={getTableColumn()}
                  size="small"
                  bordered={false}
                  dataSource={oppoCountListMemo}
                  scroll={{ x: '100vh', y: 'true' }}
                  rowKey={(res: any) => res?.id || getKeyRouter()}
                  loading={reportOppositeByStepLoading}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: commonPageSizeOptions,
                    showTotal: showTotalInfo,
                    onChange: handlePaginationChange,
                    pageSize: pageSizeObj?.rows,
                    current: pageSizeObj?.page,
                    total: oppoCountListMemo?.length,
                  }}
                />
              </div>
            </Card>
          </Col>
        </Row>
      </ScrollBarLayout>
    </div>
  );
};
